<template>
  <div style="height:100%" id="index">
    <view-box>
      <Myheader v-if='raceInfo' :raceinfo="raceInfo" :page="page"></Myheader>
      <div class="page">
        <divider>赛事信息</divider>
        <form-preview :header-label="raceInfo.name" header-value="" :body-items="raceInfoList" :footer-buttons="buttons2"></form-preview>
        <br>
        <divider ref="time">报名项目</divider>

        <div class="groupWarp" v-show="!showLoading">
          <group>
            <cell v-if='eventList.length!=0' is-link class="needsclick" v-for="(event,index) in eventList1" :key="event.id" :value='"¥"+event.shwoPrice' :title="event.name" :disabled="!getState1(event)" :inline-desc="getState(event,index)" @click.native="setProject1(event.name,event.id,raceid,event.team,event.team_max,event)"></cell>
          </group>
        </div>

      </div>

      <div class="procedure">
        <div class="title">
          <h3 class="top-title" ref="title"></h3>
          <divider v-if='!!ruleName' ref="time">{{ruleName}}</divider>
        </div>

        <div v-if='!!ruleHtml' class="content" v-html="ruleHtml"></div>
      </div>

    </view-box>
    <div>
      <div class="footerBanner">
        <!-- <div v-if="ad" class="ad" v-html="ad"></div> -->
        <!-- <img :src="imgSrc" alt=""> -->
      </div>

      <div class="button_header" id='x-bottom'>
        <x-header class="needsclick" slot="header" style="width: 100%;position: fixed;bottom: 0px;z-index: 100;max-width: 850px;margin: 0 auto;" title="立即报名" @on-click-title='popup'>

          <x-icon @click.native="showMenu=true" slot="overwrite-left" type="navicon" size="35" style="fill:#fff;position:relative;top:-8px;left:-3px;"></x-icon>

        </x-header>
        <actionsheet @on-click-menu='menuClick' v-model="showMenu" :menus="menus"></actionsheet>
      </div>

    </div>

    <group v-if='isShowEvent' ref='pop' class='needsclick'>
      <popup-radio style="display:none" @on-hide='next2' class='needsclick' title="11" :options="options3" v-model="option5">
        <template slot-scope="props" slot="each-item">
          <p class="clearfix">
            <span> {{ eventList[props.index].name}}</span>
            <span style="float:right;position: relative;top: 11px;">¥{{ eventList[props.index].rate}} </span>
            <br>
            <span style="color:#666;">{{getState(eventList[props.index])}}</span>
          </p>
        </template>
      </popup-radio>
    </group>

  </div>
</template>


<script type="text/ecmascript-6">
/* eslint-disable*/
const countTime = 60; //倒数计时60秒

const STARTSTR = "进行中"; //进行中提示
const ENDSTR = "已经结束"; //结束提示
const UNSTARTSTR = "尚未开始"; //尚未开始提示
import mixin from "@/common/js/mixin.js";
import Bus from "@/common/js/bus.js";
import Myheader from "@/common/components/myheader.vue";
import Myfooter from "@/common/components/myfooter1.vue";
import { cookie } from "vux";
import Indexlist from "@/common/components/indexlist.vue";

import {
  ViewBox,
  Divider,
  Card,
  PopupRadio,
  Radio,
  Tabbar,
  TabbarItem,
  debounce,
  XInput,
  Group,
  XButton,
  Grid,
  GridItem,
  FormPreview,
  Cell,
  LoadMore,
  Actionsheet,
  Toast,
  Confirm,
  XHeader,
  TransferDomDirective as TransferDom
} from "vux";
//axios
import qs from "qs";
import { axios } from "@/api/axios.js";
import { indexedDB } from "@/api/indexedDB.js";

import {
  isIdNumber,
  dateStringToDateTime,
  timeFormat,
  startTime,
  setTitle,
  formatCity,
  toDecimal2
} from "@/common/js/main.js";

export default {
  components: {
    ViewBox,
    Divider,
    Indexlist,
    Card,
    PopupRadio,
    Radio,
    Tabbar,
    TabbarItem,
    debounce,
    XInput,
    Group,
    XButton,
    Grid,
    GridItem,
    FormPreview,
    Cell,
    LoadMore,
    Actionsheet,
    Toast,
    Myheader,
    Confirm,
    XHeader
  },
  props: ["page", "host"],
  data() {
    return {
      options3: [],
      option5: "",
      eventList1: [],
      isShowEvent: false,
      ruleHtml: "",
      ruleName: "",
      eventList: [],
      showLoading: false,
      raceInfo: {},
      raceInfoList: [],
      buttons2: [
        {
          style: "primary",
          text: "查询报名",
          onButtonClick: name => {
            this.$router.push({
              path: "/query"
            });
          }
        }
      ]
    };
  },
  computed: {},
  beforecreate() {},
  created() {
    if (window.localStorage.getItem("pageType") == "racelist") {
      this.$router.push("/racelist");
    }
    var _this = this;
    //this._getRaceinfo();
    //console.log('---')
    Bus.$on("raceInfo", e => {
      _this.$set(this, "raceInfo", e);
      _this._getRuleHtml(e.rule);
      //console.log(this.raceInfo)
      //_this.ruleHtml=e
      //_this.raceInfo=e
      //window.localStorage.getItem
    });

    this._getEventlist();
    this.timeDate = new Date().valueOf();
  },
  mounted() {},
  methods: {
    next2() {
      var _this = this;
      //关闭弹出列表 如果有选中的值就跳转
      if (!!this.option5) {
        //console.log(123);
        //console.log(this.eventList);
        this.eventList.forEach((item, index) => {
          if (item.id == this.option5 && (!!item.url&&item.url!='0')) {
            window.location.href = item.url;
            return;
          }
        });
        //console.log('---321312')
        //console.log(this.option5)
        //console.log(this.eventList)
        //console.log(this.info)
        window.localStorage.setItem("isTeam", "fasle");
        this.eventList.forEach((item, inddex) => {
          if (item.id == this.option5) {
            if (item.team == 1) {
              window.localStorage.setItem("isTeam", "true");
            } else {
              window.localStorage.setItem("isTeam", "false");
            }
          }
        });

        window.localStorage.setItem("eventId", this.option5);
        console.log(this.page.raceid);
        window.localStorage.setItem("raceId", this.page.raceid);
        //console.log(this.raceInfo.disclaimer);
        window.localStorage.setItem("disclaimerID", this.raceInfo.disclaimer);
        if (!!this.raceInfo.disclaimer) {
          this.$router.push({ path: "./disclaimer" });
        } else {
          //如果是团队报名
          if (window.localStorage.getItem("isTeam") == "true") {
            this.$router.push({ path: "./teamlist" });
          } else {
            this.$router.push({ path: "./certificate/identity" });
          }
        }

        // if (!!this.info.disclaimer) {
        //   //如果有就跳免责申明
        //   window.localStorage.setItem("eventId", this.option5);
        //   this.$router.push({ path: "disclaimer" });
        // } else {
        //   //如果没有就跳填身份
        //   this.$router.push({ path: "disclaimer" });
        // }
      }
    },
    popup() {
      var ua = navigator.userAgent.toLowerCase();
      if (/iphone|ipad|ipod/.test(ua)) {
        this.$refs.pop.$children[0].$el.click();
        this.$refs.pop.$children[0].$el.click();
      } else if (/android/.test(ua)) {
        this.$refs.pop.$children[0].$el.click();
      } else {
        this.$refs.pop.$children[0].$el.click();
      }

      //this.$refs.pop.$children[0].$el.click();
      //this.$refs.pop.$children[0].$el.click();
    },
    // 设置报名信息
    setProject1(projectName, id, raceid, team, max, event1) {
      if (!this.getState1(event1) == true) {
        return;
      }

      if (!!event1.url) {
        window.location.href = event1.url;
        return;
      }
      //console.log('123')
      //console.log(event1)

      //console.log(this.getState(event))
      //console.log(this.getState1(event))
      let _this = this;

      //写入project,
      //indexedDB("project", "set", this.RACEID, projectName, function(a) {});
      //indexedDB("eventId", "set", this.RACEID, id, function() {});
      //console.log(raceid)
      window.localStorage.setItem("disclaimerID", this.raceInfo.disclaimer);
      window.localStorage.setItem("eventId", id);
      window.localStorage.setItem("raceId", raceid);
      window.localStorage.setItem("project", projectName);

      if (team == 1) {
        indexedDB("teamId", "remove", _this.RACEID, "", function() {
          _this.$router.push({
            path: "/teamlist",
            query: {
              max: max
            }
          });
        });
      } else {
        indexedDB("teamId", "remove", _this.RACEID, "", function() {
          _this.$router.push({
            path: "/disclaimer"
          });
        });
      }
    },
    _getRuleHtml(id) {
      this.axios
        .post(
          `${window.host}page/query`,
          qs.stringify({
            id: id
          })
        )
        .then(response => {
          if ((response.data.code = 200)) {
            this.ruleName = response.data.data.name;
            this.ruleHtml = response.data.data.content;
          } else {
          }
        });
    },
    _getEventlist() {
      var _this = this;
      this.axios
        .post(
          `${window.host}race/events`,
          qs.stringify({
            raceid: this.page.raceid,
            ke: this.page.ke
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            this.eventList1 = response.data.data;

            this.eventList1.forEach((item, index) => {
              item.shwoPrice = toDecimal2(item.price);
            });

            this.eventList = response.data.data;
            //如果邀请码项目在报名的赛事中 可通过
            let startLength = 0;
            let endLength = 0;

            for (var i = 0; i < this.eventList.length; i++) {
              response.data.data[i].rate = response.data.data[i].price >> 0;
              this.options3.push(response.data.data[i].id);

              if (
                window.localStorage.getItem("invitationEventId") &&
                window.localStorage.getItem("invitationEventId") ==
                  response.data.data[i].id
              ) {
                this.isDisabled = false;
                this.msg = "正在使用邀请码报名";
              }

              let timeDate = new Date().valueOf();
              let startDate =
                dateStringToDateTime(response.data.data[i].reg_begin) || null;
              let endDate =
                dateStringToDateTime(response.data.data[i].reg_end) || null;
              if (!!startDate && timeDate < startDate) {
                //还没开始
                startLength++;
              } else if (!!endDate && timeDate > endDate) {
                //已经结束
                endLength++;
              }
            }

            if (startLength == response.data.data.length) {
              this.msg = "报名未开始";
              this.isDisabled = true;
            } else if (endLength == response.data.data.length) {
              this.msg = "报名结束";
              this.isDisabled = true;
            } else {
              this.msg = "报名中";
              this.isDisabled = false;
            }

            this.isShowEvent = true;

            setTimeout(() => {
              let array = document.querySelectorAll(
                ".weui-cells_radio .weui-check__label"
              );

              _this.eventList.map((item, index) => {
                if (!item.reg_able && item.key != _this.inviteEventId) {
                  //不能报名
                  array[index].className =
                    "weui-cell weui-cell_radio weui-check__label disable";
                } else if (!item.reg_able) {
                  array[index].className =
                    "weui-cell weui-cell_radio weui-check__label disable";
                }
              });
            }, 500);
          }
        });

      //
    },
    _getRaceinfo() {
      this.axios
        .post(
          `${window.host}race/show`,
          qs.stringify({
            raceid: this.page.raceid
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            //赛事信息
            this.raceInfo = response.data.data;

            //免责声明
            window.localStorage.setItem(
              "disclaimerID",
              this.raceInfo.disclaimer
            );

            this._getRuleHtml(this.raceInfo.rule);

            if (!!this.raceInfo.time) {
              //处理比赛时间 精确到时分
              this.raceInfoList.push({
                label: "时间",
                value:
                  this.raceInfo.time.split(" ")[0] +
                  " " +
                  this.raceInfo.time.split(" ")[1].split(":")[0] +
                  ":" +
                  this.raceInfo.time.split(" ")[1].split(":")[0]
              });
            }

            if (!!this.raceInfo.address) {
              if (!!this.raceInfo.city) {
                //处理比赛地点
                this.raceInfoList.push({
                  label: "地点",
                  value: formatCity(this.raceInfo.city) + this.raceInfo.address
                });
              } else {
                //处理比赛地点
                this.raceInfoList.push({
                  label: "地点",
                  value: formatCity(this.raceInfo.city)
                });
              }
            }
          }
        });
    },
    getState(a) {
      let startDate = dateStringToDateTime(a.reg_begin) || null;
      let endDate = dateStringToDateTime(a.reg_end) || null;

      if (!!a.reg_begin) {
        var startTime = timeFormat(a.reg_begin);
      }

      if (!!a.reg_end) {
        var endTime = timeFormat(a.reg_end) || null;
      }

      if (
        typeof this.inviteCode !== "undefined" &&
        this.inviteEventId == a.id
      ) {
        return "报名中(正在使用邀请码报名)";
      }

      if (!a.reg_begin && !a.reg_end) {
        //没有开始时间 没有结束时间  不设置限制
        if (a.state == "audit") {
          return STARTSTR + "，需要审核";
        } else if (a.state == "draw") {
          return STARTSTR + "，需要抽签";
        } else if (a.state == "normal") {
          if (a.remain <= 0) {
            if (a.allow_wait == 0) {
              return "已经报满了";
            } else if (a.allow_wait >= 1) {
              return "候补中，有 " + a.wait_count + " 人在候补";
            }
          } else {
            return STARTSTR;
          }
        }

        return STARTSTR;
      } else if (!a.reg_begin && a.reg_end) {
        //只有结束时间
        if (this.timeDate >= endDate) {
          //大于结束时间 返回已经结束
          return ENDSTR + "(报名截止时间:" + endTime + ")";
        } else {
          //小于结束时间 返回进行中
          if (a.state == "audit") {
            return STARTSTR + "，需要审核";
          } else if (a.state == "draw") {
            return STARTSTR + "，需要抽签";
          } else if (a.state == "normal") {
            if (a.remain <= 0) {
              if (a.allow_wait == 0) {
                return "已经报满了";
              } else if (a.allow_wait >= 1) {
                return "候补中，有 " + a.wait_count + " 人在候补";
              }
            } else {
              return STARTSTR;
            }
          }

          return STARTSTR;
        }
      } else if (a.reg_begin && !a.reg_end) {
        //只有开始时间
        if (this.timeDate >= startDate) {
          //大于开始时间 返回进行中
          if (a.state == "audit") {
            return "报名中，需要审核";
          } else if (a.state == "draw") {
            return "报名中，需要抽签";
          } else if (a.state == "normal") {
            if (a.remain <= 0) {
              if (a.allow_wait == 0) {
                return "已经报满了";
              } else if (a.allow_wait >= 1) {
                return "候补中，有 " + a.wait_count + " 人在候补";
              }
            } else {
              return STARTSTR;
            }
          }

          return STARTSTR;
        } else {
          //小于开始时间 返回还未开始
          return UNSTARTSTR + "(开始时间:" + startTime + ")";
        }
      } else if (a.reg_begin && a.reg_end) {
        //正常状态，有开始和结束时间
        // if (this.timeDate >= endDate) {
        //   return ENDSTR;
        // } else if (this.timeDate <= startDate) {
        //   return UNSTARTSTR;
        // }
        // return STARTSTR
        //只有开始时间
        //console.log(this.timeDate);
        if (this.timeDate <= startDate) {
          //当前时间小于开始时间 还没开始
          return UNSTARTSTR + "(开始时间:" + startTime + ")";
        } else if (this.timeDate >= endDate) {
          //当前时间大于结束事时间 已经结束
          return ENDSTR + "(截止时间:" + endTime + ")";
        } else {
          if (a.state == "audit") {
            return STARTSTR + "，需要审核";
          } else if (a.state == "draw") {
            return STARTSTR + "，需要抽签";
          } else if (a.state == "normal") {
            if (a.remain <= 0) {
              if (a.allow_wait == 0) {
                return "已经报满了";
              } else if (a.allow_wait >= 1) {
                return "候补中，有 " + a.wait_count + " 人在候补";
              }
            } else {
              return STARTSTR;
            }
          }
          return STARTSTR;
        }
      }
    },
    getState1(a) {
      if (
        typeof this.inviteCode !== "undefined" &&
        this.inviteEventId == a.id
      ) {
        return true;
      } else if (a.reg_able) {
        return true;
      } else {
        return false;
      }
    }
  },
  directives: {
    TransferDom
  },
  mixins: [mixin]
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" rel="stylesheet/less">
#index {
  #tabbar {
    position: fixed;
    bottom: 0;
    width: 100vw;
    max-width: 850px;
  }
}

#index .page {
  .title {
    font-size: 20px;
    line-height: 2;
  }
  .message {
    line-height: 1;
  }
}

#index .warpper {
  padding: 10px;
}

.procedure {
  padding: 10px;
  background: white;
}

.procedure .title {
  margin: 10px;
  width: auto;
}

.procedure .title .top-title {
  text-align: center;
  font-weight: 400;
  // font-size: 17px;
  width: auto;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-wrap: normal;
  word-wrap: break-word;
  word-break: break-all;
}

.procedure .weui-media-box__info {
  margin-top: 15px;
  padding-bottom: 5px;
  font-size: 13px;
  color: #745e5e;
  line-height: 1em;
  list-style: none;
  overflow: hidden;
}

.weui-media-box__info__meta_extra {
  padding-left: 1em;
  border-left: 1px solid #745e5e;
}

.weui-media-box__info__meta {
  float: left;
  padding-right: 1em;
}

.procedure .content {
  margin-bottom: 20px;
  width: 100%;
  height: 100%;
}

.procedure .content p {
  margin: 10px 0 10px;
  white-space: normal;
  color: #666;
  font-size: 13px;
  line-height: 200%;
  // overflow: hidden;
  // text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  // -webkit-line-clamp: 2;
  // margin: 8px;
}

.procedure .content span {
  color: #666;
  font-size: 13px;
  line-height: 160%;

  margin: 10px;
}

.procedure .content .imgs {
  width: 100%;
  // height: 100px;
  display: table-cell;
  vertical-align: middle;
  // text-align: center;
  padding: 10px;
}

.procedure .content img {
  width: 100%;
}

//h1标签
.procedure .content {
  color: #666;
  box-sizing: border-box;
  h1 {
    font-weight: 500;
    line-height: 1.1;
    font-size: 36px;
    margin-bottom: 10px;
  }
  h2 {
    font-weight: 500;
    line-height: 1.1;
    font-size: 30px;
    margin-bottom: 10px;
  }
  h3 {
    font-weight: 500;
    line-height: 1.1;
    font-size: 24px;
    margin-bottom: 10px;
  }
  h4 {
    font-weight: 500;
    line-height: 1.1;
    font-size: 18px;
    margin-bottom: 10px;
  }
  h5 {
    font-weight: 500;
    line-height: 1.1;
    font-size: 14px;
    margin-bottom: 10px;
  }
  h6 {
    font-weight: 500;
    line-height: 1.1;
    font-size: 12px;
    margin-bottom: 10px;
  }
  ol,
  ul {
    color: #666;
    display: block;
    list-style-type: decimal;
    -webkit-margin-before: 1em;
    -webkit-margin-after: 1em;
    -webkit-margin-start: 0px;
    -webkit-margin-end: 0px;
    -webkit-padding-start: 40px;
  }
  li {
    display: list-item;
    text-align: -webkit-match-parent;
  }
  button {
    display: inline-block;
    padding: 4px 12px;
    margin-bottom: 0;
    font-size: 14px;
    line-height: 20px;
    text-align: center;
    text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
    vertical-align: middle;
    cursor: pointer;
    background-image: linear-gradient(to bottom, #fff, #e6e6e6);
    background-repeat: repeat-x;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
    border-bottom-color: #b3b3b3;
    border-radius: 4px;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
      0 1px 2px rgba(0, 0, 0, 0.05);
    &:hover,
    &:focus {
      color: #333;
      text-decoration: none;
      background-position: 0 -15px;
      -webkit-transition: background-position 0.1s linear;
      -moz-transition: background-position 0.1s linear;
      -o-transition: background-position 0.1s linear;
      transition: background-position 0.1s linear;
    }
  }
  a {
    color: #666;
    text-decoration: none;
    line-height: 1.75;
    font-size: 14px;
    &:hover {
      color: #c81623;
    }
    strong {
      font-weight: 700;
    }
  }
}

.procedure table {
  width: 100%;
  max-width: 100%;
  white-space: pre;
  border-spacing: 0;
  border-collapse: collapse;
  word-break: break-all;
  word-wrap: break-word;
}

.procedure table thead {
  display: table-header-group;
  vertical-align: middle;
  border-color: inherit;
}

.procedure .tr {
  display: table-row;
  vertical-align: inherit;
  border-color: inherit;
}

.procedure thead > tr > th {
  border-bottom-width: 2px;
  padding: 8px;
  line-height: 1.42857143;
  vertical-align: top;
  text-align: left;
  font-weight: bold;
  border: 1px solid #ddd;
  // display: table-cell;
}

.procedure tbody {
  display: table-row-group;
  vertical-align: middle;
  border-color: inherit;
}

.procedure tbody > tr > td {
  border: 1px solid #ddd;
  padding: 8px;
  line-height: 1.42857143;
  vertical-align: top;
  border-top: 1px solid #ddd;
}

.procedure tbody > tr > th {
  border: 1px solid #ddd;
  text-align: left;
  padding: 8px;
}

.disable {
  pointer-events: none;
}

#index .page .weui-form-preview__hd {
  padding-bottom: 0;
  padding-top: 20px;
  line-height: 20px;
  min-height: 20px;
  text-align: left;
      padding-right: 0;
}

#index .page .weui-form-preview__hd .weui-form-preview__label {
      float: none;
    text-align: left;
}
</style>






